package com.zhen.lucene.test;

import com.zhen.lucene.ik.IKAnalyzer6x;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;

public class IndexDocs {

    public static void main(String[] args) throws IOException {
        File newsfile = new File("chapter2/lucene-6-1/testfile/news.txt");
        String text1 = textToString(newsfile);
        Analyzer smcAnalyzer = new IKAnalyzer6x(true);
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(smcAnalyzer);
        indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
        Directory directory = FSDirectory.open(Paths.get("chapter2/lucene-6-1/indexdir"));
        IndexWriter indexWriter = new IndexWriter(directory,indexWriterConfig);
        FieldType type = new FieldType();
        type.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
        type.setStored(true);
        type.setStoreTermVectors(true);
        type.setTokenized(true);

        Document doc1 = new Document();
        Field field = new Field("content",text1,type);
        doc1.add(field);
        indexWriter.addDocument(doc1);
        indexWriter.close();
        directory.close();

    }

    private static String textToString(File newsfile) {
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(newsfile));
            String str = null;
            while((str = br.readLine()) != null){
                result.append(System.lineSeparator() + str);
            }
            br.close();
        }catch (Exception e){

        }
        return result.toString();
    }

}
